'''
执行数据获取
'''
import ast
import json
import os
import random
import threading
import time
import winreg
from datetime import datetime, timedelta

from PyQt5.QtCore import QThread, pyqtSignal
from playwright.sync_api import sync_playwright
from pandas import read_csv, read_excel
from Util.zconfig import get_setting
import chardet
import re

class WorkerThread(QThread):
    '''
    获取数据类
    '''
    # 线程信号
    upNextDate = pyqtSignal(str)  # 更新下次运行时间
    upLog = pyqtSignal(str)  # 用于更新日志的信号
    finished = pyqtSignal()  # 结束信号

    def __init__(self, page, logger,selected_browser):
        super().__init__()
        self.page = page
        self.Debug = get_setting('DEBUG')
        self.logger = logger
        self.selected_browser = selected_browser#用户选择使用的浏览器

    # 检测文件编码的函数
    def detect_encoding(self, file):
        raw_data = file.read(10000)  # 读取文件的前10000个字节进行检测
        result = chardet.detect(raw_data)
        file.seek(0)  # 重置文件指针
        return result['encoding']

    def run(self):
        def on_page_opened(page):
            global current_page
            current_page = page
            print("New page opened:", current_page.url)
        page = None
        context = None
        base_dir = os.getcwd()
        #下载文件保存地址
        download_folder = os.path.join(base_dir, 'download')
        if not os.path.exists(download_folder):
            os.makedirs(download_folder)
        auto_cookie_folder = os.path.join(base_dir, 'cookies/')

        try:
            playwright = sync_playwright().start()
        except BaseException as e:
            self.logger.error('自动化实例创建失败')
            raise
        if self.selected_browser == 'msedge':
            try:
                # 打开注册表键，获取 Microsoft Edge 的路径
                with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\msedge.exe') as key:
                    chrome_path, _ = winreg.QueryValueEx(key, None)
            except FileNotFoundError:
                self.logger.info('未找到 Microsoft Edge')
                raise
        else:
            try:
                # 打开注册表键
                with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe') as key:
                    chrome_path, _ = winreg.QueryValueEx(key, None)
            except FileNotFoundError:
                self.logger.info('未找到谷歌浏览器')
                raise

        try:
            browser = playwright.chromium.connect_over_cdp(get_setting('CDPURL'))
            browser_flag = 'Manual'  # 手动
        except BaseException as e:
            browser_flag = 'Auto'  # 自动

        cookies_name = auto_cookie_folder + 'tb/' + '巨量千川账号' + '.json'
        if browser_flag == 'Manual':
            if os.path.exists(cookies_name):
                try:
                    with open(cookies_name, 'r') as file:
                        cookies_data = json.load(file)['cookies']
                except BaseException as e:
                    self.logger.error(f'登录数据缓存文件巨量千川账号加载失败:{str(e)}')
                    raise
            else:
                self.logger.info(f'未找到巨量千川账号的缓存文件,请登录网站后点击[保存登录信息]按钮!')
                raise
            context = browser.contexts[0]
            page = context.pages[0]
            page.context.add_cookies(cookies_data)  # 使用 page.context 添加 cookies
            page.reload()  # 重新加载页面，使 cookies 生效
        else:
            # 检查文件是否存在
            if os.path.exists(cookies_name):
                try:
                    with open(cookies_name, 'r') as file:
                        cookies_data = json.load(file)['cookies']
                    user_agents = [
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Edge/91.0.864.59 Safari/537.36",
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Firefox/89.0 Safari/537.36"
                    ]
                    languages = ['en-US', 'en-GB', 'fr-FR', 'de-DE']
                    timezones = ['America/New_York', 'Europe/London', 'Asia/Tokyo', 'Australia/Sydney']
                    # 随机选择一个指纹
                    user_agent = random.choice(user_agents)
                    language = random.choice(languages)
                    timezone = random.choice(timezones)
                    path_user_data = get_setting('PATH_USER_DATA')
                    browser = playwright.chromium.launch_persistent_context(user_data_dir=path_user_data,
                                                                            executable_path=chrome_path,
                                                                            # 要想通过这个下载文件这个必然要开  默认是False
                                                                            accept_downloads=True,
                                                                            # 设置不是无头模式
                                                                            headless=False,
                                                                            bypass_csp=True,
                                                                            slow_mo=10,
                                                                            channel=f"{self.selected_browser}",
                                                                            args=[
                                                                                '--disable-blink-features=AutomationControlled',
                                                                                '--remote-debugging-port=9333',
                                                                                f'--user-agent={user_agent}',
                                                                                f'--lang={language}',
                                                                                # 设置随机语言
                                                                                f'--timezone={timezone}',
                                                                                # 设置随机时区
                                                                            ])
                    # 添加 cookies
                    browser.add_cookies(cookies_data)
                    page = browser.pages[0]

                    # 防止被检测为自动化行为
                    page.evaluate("""
                                     Object.defineProperty(navigator, 'webdriver', {get: () => undefined})
                                """)
                except BaseException as e:
                    self.logger.error(f'登录数据缓存文件{cookies_name}加载失败:{str(e)}')
                    raise
            else:
                self.logger.info(f'未找到巨量千川的缓存文件,请登录网站后点击[保存登录信息]按钮!')
                raise
        # =========================      数据获取      =========================#
        try:
            video_url = get_setting('TASK_URL')['短视频素材统计']['IN']
            page.goto(video_url)
            page.wait_for_load_state()
            time.sleep(random.randint(2, 5))
            zb_btn = page.locator('div:has-text("推直播")').first
            if zb_btn.count() > 0 :
                zb_btn.click()
            time.sleep(random.randint(2, 5))
            tj_btn = page.locator('div.report-shortcuts-datepicker-prefix-label:has-text("统计周期")')
            if tj_btn.count() > 0 :
                tj_btn.click()
            # 点击最近7天
            days7_btn = page.locator('div.ovui-shortcut.oc-range-picker-shortcut-item:has-text("最近7天")')
            if days7_btn.count() > 0 :
                days7_btn.click()
            #监听下载事件,点击下载按钮
            down_div = page.locator('.qc-report-download-btn.download-btn div').first  # 获取第一个 div 元素
            with page.expect_download() as download_info:
                down_div.click()

            download = download_info.value
            suggested_filename = download.suggested_filename

            # 保存下载的文件到指定路径
            download.save_as(os.path.join(download_folder, suggested_filename))

        except BaseException as e:
            proMsg = '--短视频素材统计获取失败:' + str(e)
            self.logger.error(proMsg)
        finally:
            try:
                context.close()
            except:
                pass
            try:
                browser.close()
            except:
                pass
        # =========================      数据获取结束      =========================#
        self.logger.info('本次线程结束')
        self.finished.emit()
